#define BUZZER_PIN 3    // 蜂鸣器引脚
#define BUTTON_PIN 7    // 按键引脚

// 歌曲选择枚举
enum Songs {HAPPY_BIRTHDAY, TWO_TIGERS} currentSong = HAPPY_BIRTHDAY;
bool buttonPressed = false;

// 生日快乐音符频率 (C大调)
int happyNotes[] = {
  523, 523, 587, 523, 698, 659, 0, 523, 523, 587, 523, 784, 698, 0,
  523, 523, 1047, 880, 698, 659, 587, 0, 988, 988, 880, 698, 784, 698
};

// 生日快乐音符时长
int happyDurations[] = {
  250, 250, 500, 500, 500, 1000, 250, 250, 250, 500, 500, 500, 1000, 250,
  250, 250, 500, 500, 500, 500, 1000, 250, 250, 250, 500, 500, 500, 1000
};

// 两只老虎音符频率 (C大调)
int tigerNotes[] = {
  523, 587, 659, 523, 0, 523, 587, 659, 523, 0, 659, 698, 784, 0,
  659, 698, 784, 0, 784, 880, 784, 698, 659, 523, 0, 784, 880, 784, 698, 659, 523
};

// 两只老虎音符时长
int tigerDurations[] = {
  250, 250, 250, 250, 250, 250, 250, 250, 250, 250, 250, 250, 500, 250,
  250, 250, 500, 250, 250, 250, 250, 250, 250, 250, 250, 250, 250, 250, 250, 250, 500
};

void setup() {
  pinMode(BUZZER_PIN, OUTPUT);
  pinMode(BUTTON_PIN, INPUT_PULLUP);  // 按键上拉输入
}

void loop() {
  // 按键检测 (带防抖)
  if (digitalRead(BUTTON_PIN) == LOW && !buttonPressed) {
    delay(50);  // 防抖延时
    if (digitalRead(BUTTON_PIN) == LOW) {
      currentSong = (currentSong == HAPPY_BIRTHDAY) ? TWO_TIGERS : HAPPY_BIRTHDAY;
      buttonPressed = true;
      noTone(BUZZER_PIN);  // 切换时停止当前播放
    }
  }
  if (digitalRead(BUTTON_PIN) == HIGH) buttonPressed = false;

  // 根据当前歌曲播放
  if (currentSong == HAPPY_BIRTHDAY) {
    playSong(happyNotes, happyDurations, sizeof(happyNotes)/sizeof(happyNotes[0]));
  } else {
    playSong(tigerNotes, tigerDurations, sizeof(tigerNotes)/sizeof(tigerNotes[0]));
  }
  delay(2000);  // 播放间隔
}

// 音乐播放函数
void playSong(int notes[], int durations[], int length) {
  for (int i = 0; i < length; i++) {
    if (notes[i] == 0) {
      noTone(BUZZER_PIN);
    } else {
      tone(BUZZER_PIN, notes[i]);
    }
    delay(durations[i]);
    // 播放中检测按键
    if (digitalRead(BUTTON_PIN) == LOW) return;
  }
  noTone(BUZZER_PIN);
}
